package com.choosefine.it.basedata.service;

import com.choosefine.it.basedata.dao.ProjectTypeMapper;
import com.choosefine.it.basedata.model.ProjectType;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目类型service
 * @author 潘钱钦
	下午2:42:52
 *
 */
@Service("projectTypeService")
public class ProjectTypeService{
	@Autowired
	private ProjectTypeMapper projectTypeMapper;

	public ProjectType getProjectTypeById(Integer id) {
		
		return projectTypeMapper.selectByPrimaryKey(id);
	}
	/* (non-Javadoc)
	 * @see com.choosefine.it.basedata.service.ProjectTypeService#getProjectTypeList(java.util.List)
	 */
	public List<ProjectType> getProjectTypeList(List<Integer> ids) {
		return projectTypeMapper.selectListByIds(ids);
	}
	/**
	 * 第二版用户排序——修改
	 * 
	 * update by juchengyang 2017/2/16
	 */
	public int deleteByPrimaryKey(Integer id) {
		int num = 0;
		ProjectType deleteProjectTypeUp = projectTypeMapper.selectProjectTypeBySortNum(id);
		ProjectType deleteProjectType = projectTypeMapper.selectByPrimaryKey(id);
		if(null != deleteProjectTypeUp){
			deleteProjectTypeUp.setSortNum(deleteProjectType.getSortNum());
			num += projectTypeMapper.updateByPrimaryKeySelective(deleteProjectTypeUp);
		}
		num += projectTypeMapper.deleteByPrimaryKey(id);
		return num;
	}

	public int insert(ProjectType record) throws BusinessException {
		//工程类型唯一校验
		int count = projectTypeMapper.checkProjectTypeInsert(record.getProjectType());
		if(count != 0){
			throw new BusinessException(ResultCode.FAILED,CommonConstant.IS_EXISTS);
		}
		int num = 0;
		ProjectType lastProjectType = projectTypeMapper.selectProjectTypeBySortNum(0);
		if(null != lastProjectType){
			record.setSortNum(-1);
			num += projectTypeMapper.insert(record);
			record = projectTypeMapper.selectProjectTypeBySortNum(-1);
			lastProjectType.setSortNum(record.getId());
			record.setSortNum(0);
			record.setIsValid(null);
			lastProjectType.setIsValid(null);
			num += projectTypeMapper.updateByPrimaryKeySelective(record);
			num += projectTypeMapper.updateByPrimaryKeySelective(lastProjectType);
		}else{
			record.setSortNum(0);
			num += projectTypeMapper.insertSelective(record);
		}
		return num;
	}

	public int update(ProjectType record) {
		return projectTypeMapper.updateByPrimaryKey(record);
	}
	/**
	 * add by juchengyang
	 *  juchengyang 2017年2月17日
	 * @throws BusinessException 
	 */
	public int updateByPrimaryKeySelective(ProjectType record) throws BusinessException{
		//工程类型唯一校验
		int count = projectTypeMapper.checkProjectTypeInsert(record.getProjectType());
		if(count != 0){
			throw new BusinessException(ResultCode.FAILED,CommonConstant.IS_EXISTS);
		}
		return projectTypeMapper.updateByPrimaryKeySelective(record);
	}
	
	public List<ProjectType> findAllByPage() throws BusinessException {
		//查询数据库返回列表
		List<ProjectType> getList = projectTypeMapper.getProjectList();
		if(getList.size()==0){
			return new ArrayList<ProjectType>();
		}
		List<ProjectType> returnList = listOrderBySorNum(getList);		
		return returnList;
	}
	private List<ProjectType> listOrderBySorNum(List<ProjectType> getList) throws BusinessException {
		checkList(getList);
		int size = getList.size();
		List<ProjectType> returnList = new ArrayList<>();
		for(ProjectType temp:getList){
			//最后一位 sortNum 为0
			if(0 == temp.getSortNum()){
				returnList.add(temp);
			}
		}
		ProjectType tempProjectType = returnList.get(0);
		while(returnList.size()<size){
			for(int i = 0; i<size; i++){
				if(tempProjectType.getId().equals(getList.get(i).getSortNum())){
					returnList.add(getList.get(i));
					tempProjectType = getList.get(i);
				}
				if(i == size-1){
					
				}
			}
		}
		for(int i=0; i<size/2; i++){
			ProjectType tempProjecType = returnList.get(i);
			returnList.set(i, returnList.get(size-i-1));
			returnList.set(size-i-1, tempProjecType);
		}
		return returnList;
	}
	/**
	 * 不分页（毛俊）
	 * @return
	 */
	public List<ProjectType> findAllProjectType() {
		
		return projectTypeMapper.getProjectList();
	}
	public int projectTypeOrderUp(Integer fromId,Integer toId){
		int num = 0;
		ProjectType fromProjectType = null;
		ProjectType fromProjectTypeUp = null;
		ProjectType toProjectTypeUp = null;
		fromProjectType = projectTypeMapper.selectByPrimaryKey(fromId);
		fromProjectTypeUp = projectTypeMapper.selectProjectTypeBySortNum(fromId);
		toProjectTypeUp = projectTypeMapper.selectProjectTypeBySortNum(toId);
		if(toProjectTypeUp == null){
			fromProjectTypeUp.setSortNum(fromProjectType.getSortNum());
			fromProjectType.setSortNum(toId);
		}else{
			fromProjectTypeUp.setSortNum(fromProjectType.getSortNum());
			fromProjectType.setSortNum(toId);
			toProjectTypeUp.setSortNum(fromId);
		}
		if(null != toProjectTypeUp){
			toProjectTypeUp.setIsValid(null);
			num += projectTypeMapper.updateByPrimaryKeySelective(toProjectTypeUp);
		}
		fromProjectType.setIsValid(null);
		fromProjectTypeUp.setIsValid(null);
		num += projectTypeMapper.updateByPrimaryKeySelective(fromProjectType);
		num += projectTypeMapper.updateByPrimaryKeySelective(fromProjectTypeUp);
		return num;
	}
	public int projectTypeOrderDown(Integer fromId,Integer toId){
		int num = 0;
		ProjectType fromProjectType = null;
		ProjectType fromProjectTypeUp = null;
		ProjectType toProjectType = null;
		fromProjectType = projectTypeMapper.selectByPrimaryKey(fromId);
		fromProjectTypeUp = projectTypeMapper.selectProjectTypeBySortNum(fromId);
		toProjectType = projectTypeMapper.selectByPrimaryKey(toId);
		if(fromProjectTypeUp == null){
			fromProjectType.setSortNum(toProjectType.getSortNum());
			toProjectType.setSortNum(fromId);
		}else{
			fromProjectTypeUp.setSortNum(fromProjectType.getSortNum());
			fromProjectType.setSortNum(toProjectType.getSortNum());
			toProjectType.setSortNum(fromId);
		}
		if(null != fromProjectTypeUp){
			fromProjectTypeUp.setIsValid(null);
			num += projectTypeMapper.updateByPrimaryKeySelective(fromProjectTypeUp);
		}
		num += projectTypeMapper.updateByPrimaryKeySelective(fromProjectType);
		num += projectTypeMapper.updateByPrimaryKeySelective(toProjectType);
		return num;
	}
	public List<ProjectType> selectAllProjectType() throws BusinessException{
		//查询数据库返回列表
		List<ProjectType> getList = projectTypeMapper.getProjectList();
		List<ProjectType> returnList = listOrderBySorNum(getList);
		return returnList;
	}
	/**
	 * 添加，根据name查询
	 *  juchengyang 2017年2月17日
	 */
	public PageInfo<ProjectType> selectProjectTypeByName(Map<String,Object> map, Integer pageNum, Integer pageSize){
		Map<String, Object> conditionMap = new HashMap<>();
		pageNum = pageNum == null?1:pageNum;
		pageSize = pageSize == null?10:pageSize;
		PageHelper.startPage(pageNum, pageSize);
		return new PageInfo<ProjectType>(projectTypeMapper.selectProjectTypeBy(map));
	}
	/*
	 * 数据校验
	 */
	public void checkList (List<ProjectType> list) throws BusinessException {
    	Map<Integer, Integer> keyMap = new HashMap<Integer, Integer>();
        Map<Integer, Integer> nextMap = new HashMap<Integer, Integer>();
        for( ProjectType n: list){
        	if (nextMap.containsKey(n.getSortNum())) {
        		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//                logger.info("数据出错：next重复");
            }
        	if (n.getSortNum().equals(n.getId())) {
        		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//                logger.info("数据出错：指向自己");
            }
        	keyMap.put(n.getId(), n.getSortNum());
            nextMap.put(n.getSortNum(), 0);
        }
        if(!nextMap.containsKey(0)){
        	throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//        	logger.info("数据出错：不存在0（最后一位标识）");
        }
        for (ProjectType n : list) {
            Integer next = keyMap.get(n.getId());
            if (next.equals(0)) {
            	if(!nextMap.containsKey(n.getId()) && nextMap.size()>1){
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info("没有指向最后一位的");
            	}
            	if(nextMap.get(next).equals(1)){
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info("数据出错，最后一位不唯一");
            	}else{
            		nextMap.put(next, 1);
            	}
            	
            } else {
            	if(keyMap.containsKey(next)){
	            	if(nextMap.get(next).equals(1)){
	            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//	            		logger.info("数据出错，"+next+"重复");
	            	}else{
	            		nextMap.put(next, 1);
	            	}
            	}else{
            		throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//            		logger.info(next+" 没有对应的 id");
            	}
            }

        }
        if(nextMap.containsValue(0)){
        	throw new BusinessException(ResultCode.FAILED,CommonConstant.DATA_NEXT);
//        	logger.info("next 有无效值");
        }
    }
	public PageInfo<ProjectType> selectProjectTypeList(Integer pageSize, Integer pageNum){
		pageNum = pageNum == null?1:pageNum;
		pageSize = pageSize == null?10:pageSize;
		PageHelper.startPage(pageNum, pageSize);
		return new PageInfo<ProjectType>(projectTypeMapper.getProjectList());
	}
}
